package com.matrix.draft.rabbitmqspringboot.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 发布确认RabbitMQ配置(高级)
 */
@Configuration
@EnableRabbit
public class AdvanceRabbitMQConfig {


    public static final String exchangeConfirm = "exchange_confirm";
    public static final String queueConfirm = "queue_confirm";
    public static final String routingKey = "routing_key_1";
    public static final String exchangeSpare = "exchange_spare";
    public static final String queueBackup = "queue_backup";
    public static final String queueWarn = "queue_warn";

    // 交换机
    @Bean
    Exchange exchangeConfirm() {
        return ExchangeBuilder.directExchange(exchangeConfirm)
                .autoDelete()
                .alternate(exchangeSpare)
                .build();
    }

    // 队列(有优先级功能)
    @Bean
    Queue queueConfirm() {
        return QueueBuilder.durable(queueConfirm)
                .maxPriority(10)
                .build();
    }

    // 绑定
    @Bean
    Binding bindingQueue2Exchange(
            @Qualifier("queueConfirm") Queue queueConfirm,
            @Qualifier("exchangeConfirm") Exchange exchangeConfirm
    ) {
        return BindingBuilder.bind(queueConfirm).to(exchangeConfirm).with(routingKey).noargs();
    }

    // 处理不可达消息的备份交换机
    @Bean
    Exchange exchangeSpare(){
        return ExchangeBuilder.fanoutExchange(exchangeSpare).autoDelete().build();
    }

    // 用于数据备份的队列
    @Bean
    Queue queueBackup(){
        return QueueBuilder.durable(queueBackup).build();
    }

    // 用于报警的队列
    @Bean
    Queue queueWarn(){
        return QueueBuilder.durable(queueWarn).build();
    }

    // 数据备份队列,备份交换机绑定
    @Bean
    Binding bindingQueueBackup2ExchangeSpare(
            @Qualifier("queueBackup") Queue queueBackup,
            @Qualifier("exchangeSpare") Exchange exchangeSpare
    ){
        return BindingBuilder.bind(queueBackup).to(exchangeSpare).with("").noargs();
    }

    // 备份队列,报警队列与备份交换机绑定
    @Bean
    Binding bindingQueueWarn2ExchangeSpare(
            @Qualifier("queueWarn") Queue queueWarn,
            @Qualifier("exchangeSpare") Exchange exchangeSpare
    ){
        return BindingBuilder.bind(queueWarn).to(exchangeSpare).with("").noargs();
    }
}
